package constant;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;

import javax.swing.*;

public class FreeMarkerConfig {

	public static Configuration configuration = new Configuration();

	static {
		try {
			String ftlPath = Constant.modelFiles;
			ftlPath = URLDecoder.decode(ftlPath, "utf-8");
			File file = new File(ftlPath);

			if (!file.exists()) {
				file.mkdir();
			}

			MultiTemplateLoader multiTemplateLoader = setFtlFloder(file);
			configuration.setTemplateLoader(multiTemplateLoader);
			configuration.setDefaultEncoding("UTF-8");
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "加载模板时出错！" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * 设置ftl模板
	 *
	 * @param file
	 * @throws IOException
	 */
	private static MultiTemplateLoader setFtlFloder(File file) throws IOException {

		List<TemplateLoader> templateLoaders = new ArrayList<>();
		addTemplate(file, templateLoaders);
		return new MultiTemplateLoader(templateLoaders.toArray(new TemplateLoader[0]));
	}

	private static void addTemplate(File file, List<TemplateLoader> templateLoaders) throws IOException {
		for (File currentFile : Objects.requireNonNull(file.listFiles())) {
			if (currentFile.isDirectory()) {
				FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(currentFile);
				templateLoaders.add(fileTemplateLoader);
				addTemplate(currentFile, templateLoaders);
			}
		}
	}

}
